package com.example.bootbook.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import com.example.bootbook.domain.Book;
import com.example.bootbook.domain.Result;
import com.example.bootbook.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/books")
@Api("图书控制器")
public class BookController {

    @Resource
    private BookService bookService;

    @GetMapping("/")
    @ApiOperation("图书列表")
    public List<Book> findBooks(){
        return  this.bookService.list();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("根据id删除")
    public Result<Boolean> delete(@PathVariable int id){
         return  this.bookService.removeById(id)
                 ? new Result(200,true)
                 : new Result(300,false);
    }

    @DeleteMapping("/")
    @ApiOperation("批量删除")
    public Result<Boolean> batch_delete(Integer[] ids){
        return  this.bookService.removeByIds(Arrays.asList(ids))
                ? new Result(200,true)
                : new Result(300,false);
    }

    @PostMapping("/")
    @ApiOperation("新增图书")
    public Result<Boolean> add(@RequestBody Book book){
        return  this.bookService.save(book)
                ? new Result(200,true)
                : new Result(300,false);
    }

    @PutMapping("/")
    @ApiOperation("修改图书")
    public Result<Boolean> update(@RequestBody Book book){
        return  this.bookService.updateById(book)
                ? new Result(200,true)
                : new Result(300,false);
    }

    @Value("${server.port}")
    private String port;

    private static final String ip="http://localhost";

    private static  final  String path= System.getProperty("user.dir")+"/boot-book/src/main/resources/upload/";
    /**
     * 上传图片的方法，参数名必须是file： <input type='file' name='file'>
     * @param file
     * @return
     */
    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public Result upload(MultipartFile file){

        System.out.println(path);
        //生成唯一的id（防止文件重名）
        String id= IdUtil.fastSimpleUUID();
        String originalFilename = file.getOriginalFilename();
        String imgPath= path+id+"_"+originalFilename;
        System.out.println(imgPath);
        try {
            FileUtil.writeBytes(file.getBytes(),imgPath);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(303, false, "上传失败！");
        }
        return new Result(200, true, "上传成功", ip+":"+this.port+"/books/"+id);
    }

    @GetMapping("/{flag}")
    @ApiOperation("文件下载")
    public void downFile(@PathVariable String flag, HttpServletResponse response) {
        OutputStream outputStream = null;
        File file = new File(path);
        List<String> list = Arrays.asList(file.list());
        String fileName = list.stream().filter(name -> name.contains(flag)).findAny().orElse("");
        if (fileName != null && !fileName.isEmpty()) {
            try {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
                response.setContentType("application/octet-stream");

                byte[] arr = FileUtil.readBytes(path + fileName);
                outputStream = response.getOutputStream();
                outputStream.write(arr);
                outputStream.flush();
                outputStream.close();
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
